//
//  DDStatus.swift
//  SinaMicroBlogSwift2
//
//  Created by dqw on 15/8/3.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

class DDStatus: NSObject {
    
    var created_at: String?
    var id: Int = 0
    var text: String?
    var source: String? {
        didSet {
            source = source?.sourceText().source
        }
    }
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            
            if pic_urls?.count == 0 {
                return
            }
            
             storedPictureUrls = [NSURL]()
            storedLargePictureUrls = [NSURL]()
            
            for dict in pic_urls! {
                if let urlName = dict["thumbnail_pic"] as? String {
                    storedPictureUrls?.append(NSURL(string: urlName)!)
                    let largeUrlName = urlName.stringByReplacingOccurrencesOfString("thumbnail", withString: "large" )
                        storedLargePictureUrls?.append(NSURL(string: largeUrlName)!)
                }
            }
        }
    }
    
    var storedPictureUrls: [NSURL]?
   var storedLargePictureUrls: [NSURL]?
    var pictureUrls: [NSURL]? {
        return retweeted_status == nil ? storedPictureUrls : retweeted_status?.storedPictureUrls
//        return storedPictureUrls
    }
    var pictureLargeUrls: [NSURL]? {
        return retweeted_status == nil ? storedLargePictureUrls : retweeted_status?.storedLargePictureUrls
        //        return storedPictureUrls
    }

    var user: DDUser?
    //MARK: - 和后面混存行高的判断方法结合使用
    var rowHeight:CGFloat?
    var retweeted_status: DDStatus?

    // MARK: - init方法。
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // MARK: - 加载statuses
//    typealias DDFinishedCT = (statuses: [DDStatus]?, error: NSError?) -> Void
    class func loadStatuses(since_id: Int, max_id: Int, finished:(statuses: [DDStatus]?, error: NSError?) -> Void) {
        
        DDNetTools.sharedNetTools.loadStatuses(since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                finished(statuses: nil, error: error)
                return
            }
            if let arr = result!["statuses"] as? [[String: AnyObject]] {
                var statuses = [DDStatus]()
                for dict in arr {
                    statuses.append(DDStatus(dict: dict))
                }
                finished(statuses: statuses, error: nil)
                self.cacheWebImage(statuses)
            }else {
                finished(statuses: nil, error: DDNetError.wrongDataFormatError.error())
            }
        }
    }
//    , finished:(statuses: [DDStatus]?, error: NSError?) -> Void
    // MARK: - 任务组，为了保证判断所有的图片都下载完成。notify。
     // TODO: 要将传递数据完善。
    private class func cacheWebImage(statuses: [DDStatus]) {
        
        let group = dispatch_group_create()
        var dataLength = 0
        
        for status in statuses {
            
            guard let urls = status.pictureUrls else {
                continue
            }
            
            for url in urls {

                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) in
                    
                    if image != nil {
                       let data = UIImagePNGRepresentation(image)
                         dataLength += data!.length
                    }
                    
                    dispatch_group_leave(group)
                })
            }
        }
        // MARK: 这个很重要的，是等图片现在完成后，在将status的数据传递出去，即延迟了数据的传递。虽然图片和数据的存储不在一个地方。
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
        }
    }
    // MARK: - 定义user属性的setvalue方法。对于类型不匹配的属性，要重写该方法对其单独进行处理。
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                user = DDUser(dict: dict)
            }
            return
        }
        
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject]{
               retweeted_status = DDStatus(dict: dict)
            }
            return
            
        }
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        
        let properties = ["created_at", "id", "text", "source", "pic_urls", "user"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
}
